<?php
/**
 * | ---------------------------------------------------------------------------------------------------
 * | ProjectName: php
 * | ---------------------------------------------------------------------------------------------------
 * | Author：johnxu <fsyzxz@163.com>
 * | ---------------------------------------------------------------------------------------------------
 * | Home: https://www.xfjpeter.cn
 * | ---------------------------------------------------------------------------------------------------
 * | Data: 201908042019-08-04
 * | ---------------------------------------------------------------------------------------------------
 * | Desc:
 * | ---------------------------------------------------------------------------------------------------
 */

namespace app\admin\controller;

class Seat extends Base
{
    protected function _initialize()
    {
        $this->model    = model('Seat');
        $this->validate = validate('Seat');
        parent::_initialize();
    }

    /**
     * 添加座位
     */
    public function add()
    {
        $data = $this->request->post();
        if (!$this->validate->scene('add')->check($data)) {
            $this->fail(200, 1, (string)$this->validate->getError());
        } else {
            // 构造map结构为：[{"value": "@", "type": "@"}, {"value": "@", "type": "@"}, {"value": 1, "type": 1}]
            $data['map'] = $this->map($data['map']);
            unset($map);
            $insertId = $this->model->insertGetId($data);
            if ($insertId) {
                $data['id'] = $insertId;
                $this->ok(200, $data);
            } else {
                $this->fail(200, 1, '添加失败');
            }
        }
    }

    /**
     * 修改
     * @param int $id
     */
    public function edit(int $id = 0)
    {
        $row = $this->model::get($id);
        if (!$row) {
            $this->fail(200, 1, '该数据不存在');
        }
        $params        = $this->request->post();
        $params['map'] = $this->map($params['map']);
        $flag          = $row->data($params)->save();
        if ($flag !== false) {
            $this->ok(200, $row->getData());
        } else {
            $this->fail(200, 1, '修改失败');
        }
    }

    /**
     * 创建map
     * @param $data
     * @return mixed
     */
    protected function map($data)
    {
        foreach ($data as &$map) {
            foreach ($map as &$item) {
                if (isset($item['no'])) {
                    $item['type'] = $item['no'];
                } else {
                    $item = [
                        'no'   => $item,
                        'type' => $item,
                    ];
                }
            }
        }

        return $data;
    }
}